package world.criver.h50529.function;

import com.fazecast.jSerialComm.SerialPort;
import world.criver.h50529.data.daData;
import world.criver.h50529.module.moEvent;

import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class funSerial {
    /**
     * 初始化所有串口信息
     */
    public void iniSerialPorts(){
        daData.serialPorts= SerialPort.getCommPorts();
    }

    /**
     * 串口发送
     * @param event
     * @return
     */
    public String send(moEvent event){
        SerialPort port=SerialPort.getCommPort(event.getSerial());
        port.setBaudRate(event.getBaud_rate());
        port.setNumDataBits(event.getNum_data_bit());
        port.setNumStopBits(event.getNum_stop_bit()==1?SerialPort.ONE_STOP_BIT:(event.getNum_stop_bit()==1.5?SerialPort.ONE_POINT_FIVE_STOP_BITS:
                SerialPort.TWO_STOP_BITS));
        port.setParity(event.getParity().equals("奇校验")?SerialPort.ODD_PARITY:(event.getParity().equals("偶校验")?SerialPort.EVEN_PARITY:
                (event.getParity().equals("1校验")?SerialPort.MARK_PARITY:(event.getParity().equals("0校验")?SerialPort.SPACE_PARITY:SerialPort.NO_PARITY))));
        if(!port.openPort())return "串口打开失败";
        byte[] bs=null;
        funMessageFormat mf=new funMessageFormat();
        if(event.getMessage_type().equalsIgnoreCase("hex"))bs=mf.hexToByte(event.getSend_data());
        else bs=event.getSend_data().getBytes(StandardCharsets.UTF_8);
        int num=port.writeBytes(bs,bs.length);
        bs=new byte[1024];
        int a=port.readBytes(bs,bs.length);
        String read="";
        if(a>0)read=new String(bs,0,a);
        port.closePort();
        return "已发送 "+num+" 字节。返回："+read;
    }
}
